﻿using System;
using System.Threading;
using System.Windows.Forms;
using Ast.Framework.Environment;
using Ast.Framework.Environment.Extensions;
using Ast.Framework.Forms;

namespace Ast.Keyboard
{
    public class Extension : IExtension
    {
        private Form _form;

        public ExtensionLoadResult Load(IHostContainer hostContainer)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            var formFactory = hostContainer.Resolve<IFormFactory>();
            _form = formFactory.Create(typeof(KeyboardForm));

            Application.Run(_form);

            return new ExtensionLoadResult {CanUnload = true};
        }

        public ExtensionUnLoadResult Unload()
        {
            EnsureFormHandleCreated(2000);
            DisposeForm();
            return new ExtensionUnLoadResult();
        }

        private void EnsureFormHandleCreated(int timeout)
        {
            const int interval = 10;
            while ((_form == null || (!_form.IsHandleCreated && !_form.Disposing && !_form.IsDisposed)) && timeout > 0)
            {
                Thread.Sleep(interval);
                timeout -= interval;
            }
        }

        private void DisposeForm()
        {
            if (_form != null && _form.IsHandleCreated && !_form.Disposing && !_form.IsDisposed)
            {
                _form.Invoke(new Action(() => _form.Close()));
            }
        }
    }
}